﻿
using IOA.MES.Client.Models.Response;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace IOA.MES.Client.Common
{
    public class OSSUtil
    {
        public static ResultJson<OSSUploadResponse> Upload(Stream stream, string bucket, string fileName)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("");// ($"{BaseEnv.OssPath}?bucket={System.Web.HttpUtility.UrlEncode(bucket)}&fileName={System.Web.HttpUtility.UrlEncode(fileName)}");
            request.Method = "POST";
            var postStream = new MemoryStream();
            #region 处理Form表单文件上传
            //通过表单上传文件
            string boundary = "----" + DateTime.Now.Ticks.ToString("x");
            string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";


            try
            {
                //准备文件流
                var formdata = string.Format(formdataTemplate, "", fileName.Substring(fileName.LastIndexOf("/") + 1, fileName.Length - fileName.LastIndexOf("/") - 1));
                var formdataBytes = Encoding.UTF8.GetBytes(postStream.Length == 0 ? formdata.Substring(2, formdata.Length - 2) : formdata);//第一行不需要换行
                postStream.Write(formdataBytes, 0, formdataBytes.Length);

                //写入文件
                byte[] buffer = new byte[stream.Length];
                int bytesRead = 0;
                stream.Seek(0, SeekOrigin.Begin);
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    postStream.Write(buffer, 0, bytesRead);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            //结尾
            var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
            postStream.Write(footer, 0, footer.Length);
            request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
            #endregion

            request.ContentLength = postStream != null ? postStream.Length : 0;
            request.Accept = "*/*";
            //request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            request.KeepAlive = true;
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";

            #region 输入二进制流
            if (postStream != null)
            {
                postStream.Position = 0;

                //直接写入流
                Stream requestStream = request.GetRequestStream();

                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }

                postStream.Close();//关闭文件访问
            }
            #endregion

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader myStreamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
                    {
                        string retString = myStreamReader.ReadToEnd();
                        return JsonConvert.DeserializeObject<ResultJson<OSSUploadResponse>>(retString);
                    }
                }
            }
            catch (WebException ex)
            {
                return new ResultJson<OSSUploadResponse>(500, $"UploadFailed：{ex.Message}");
            }
            catch (Exception ex)
            {
                return new ResultJson<OSSUploadResponse>(500, $"UploadException：{ex.Message}");
            }
        }
    }
}
